import '../models/api_response.dart';
import '../models/friend_model.dart';
import '../services/api_service.dart';
import '../constants/api_endpoints.dart';

class FriendRepository {
  final ApiService _apiService;

  FriendRepository(this._apiService);

  /// 获取好友列表
  Future<ApiResponse<List<FriendModel>>> getFriends() async {
    final response = await _apiService.get<dynamic>(
      ApiEndpoints.imFriends,
      fromJson: (json) => json,
    );

    // 处理响应数据：可能是 {friends: [...]} 或直接是 [...]
    List<FriendModel> friends = [];
    if (response.success && response.data != null) {
      final data = response.data!;
      
      // 检查是否是直接返回的数组
      if (data is List) {
        friends = data
            .map((item) => FriendModel.fromJson(item as Map<String, dynamic>))
            .toList();
      }
      // 检查是否是 {friends: [...]} 格式
      else if (data is Map<String, dynamic>) {
        if (data.containsKey('friends') && data['friends'] is List) {
          final friendsList = data['friends'] as List;
          friends = friendsList
              .map((item) => FriendModel.fromJson(item as Map<String, dynamic>))
              .toList();
        }
        // 检查是否是 {data: [...]} 格式
        else if (data.containsKey('data') && data['data'] is List) {
          final friendsList = data['data'] as List;
          friends = friendsList
              .map((item) => FriendModel.fromJson(item as Map<String, dynamic>))
              .toList();
        }
      }
    }

    return ApiResponse<List<FriendModel>>(
      code: response.code,
      message: response.message,
      data: friends,
      success: response.success,
    );
  }

  /// 添加好友
  Future<ApiResponse<void>> addFriend(int friendId) async {
    final response = await _apiService.post<void>(
      ApiEndpoints.imFriendsAdd,
      data: {'to_id': friendId},
    );

    return response;
  }

  /// 删除好友
  Future<ApiResponse<void>> removeFriend(int friendId) async {
    final response = await _apiService.delete<void>(
      ApiEndpoints.imFriendsDelete(friendId.toString()),
    );

    return response;
  }

  /// 更新好友备注
  Future<ApiResponse<void>> updateRemark(int friendId, String remark) async {
    final response = await _apiService.put<void>(
      ApiEndpoints.imFriendsRemark(friendId.toString()),
      data: {'remark': remark},
    );

    return response;
  }
}

